from flask import Blueprint, request, session
relation_api = Blueprint("relation", __name__, url_prefix="/relation")
from toutiao.model.db_routing import User, Relation
from toutiao.model.db_routing import db


@relation_api.route("/follow", methods=("POST", "GET"))
def follow():
    if request.method == "POST":
        user_id = request.form.get('id')
        target_user_id = request.form.get('target')

        target_user = User.query.filter_by(id=target_user_id).first()
        if not target_user:
            return {'code': 200, 'msg': '目标用户不存在'}

        relation = Relation.query.filter_by(user_id=user_id, target_user_id=target_user_id, relation=1).first()
        if not relation:
            rela = Relation(user_id=user_id, target_user_id=target_user_id, relation=1)
            db.session.add(rela)

        else:
            relation.is_deleted = 0

            db.session.commit()

        # 关注人数+1
        user = User.query.filter_by(id=user_id).first()
        user.following_count += 1

        return {'code': 200, 'msg': '关注成功'}

    else:
        user_id = session.get('user')
        real = Relation.query.filter_by(user_id=user_id, is_deleted=0).all()
        a = []
        data = []
        for x in real:
            a.append(x.target_user_id)
        for x in a:
            info = User.query.filter_by(id=x).first()
            d = {
                'account': info.account,
                'sex': info.sex,
                'phone': info.phone,

            }
            data.append(d)

        return {'code': '200', 'msg': '关注的用户信息', 'data': data}


@relation_api.route('/delete_relation', methods=['POST'])
def follow_delete():
    user_id = request.form.get('id')
    target_user_id = request.form.get('target')

    real = Relation.query.filter_by(user_id=user_id, target_user_id=target_user_id).first()
    if real:
        real.is_deleted = 1
        db.session.commit()

    else:
        return {'msg': '不存在'}

    # user发起关注的人的关注人数-1
    user = User.query.filter_by(id=user_id).first()
    user.following_count -= 1

    # 3、user被关注的人的粉丝人数-1
    user = User.query.filter_by(id=target_user_id).first()
    user.fans_count -= 1
    return {'msg': '取消关注成功'}
